package com.bjgraphite.report.response;



import com.bjgraphite.report.enums.BizErrorCode;
import com.bjgraphite.report.exception.BaseException;

import java.io.Serializable;

/**
 * 统一响应的封装类
 *
 * @author zhouxiaolong
 * @date 2020/9/3 10:01
 */
public class CommonResponse<T> implements Serializable {

    /**
     * 响应码
     */
    private int code = BizErrorCode.SYSTEM_SUCCESS.getCode();
    /**
     * 响应消息
     */
    private String message;
    /**
     * 响应数据
     */
    private T data;

    /**
     * 正常返回，有数据
     * has data
     *
     * @param data
     */
    public CommonResponse(T data) {
        this.data = data;
    }

    /**
     * 正常返回，无数据
     * no data
     */
    public CommonResponse() {
    }

    /**
     * 错误状态返回
     * return error status code
     *
     * @param status
     */
    public CommonResponse(BizErrorCode status) {
        this.code = status.getCode();
        this.message = status.getMessage();
    }

    private CommonResponse(Exception exception) {
        if (exception instanceof BaseException) {
            BaseException ex = (BaseException) exception;
            this.code = ex.getBizErrorCode().getCode();
            this.message = ex.getBizErrorCode().getMessage();
        }

    }

    /**
     * 错误状态返回
     * return error status code & message
     *
     * @param message
     * @param code
     */
    private CommonResponse(String message, int code) {
        this.message = message;
        this.code = code;
    }


    private CommonResponse(T data, String message, BizErrorCode bizErrorCode) {
        this.message = message;
        this.code = bizErrorCode.getCode();
        this.data = data;
    }

    public CommonResponse(T data, BizErrorCode bizErrorCode) {
        this.data = data;
        this.message = bizErrorCode.getMessage();
        this.code = bizErrorCode.getCode();
    }

    public static <T> CommonResponse<T> buildError(BizErrorCode bizErrorCode) {
        return new CommonResponse(null, bizErrorCode);
    }

    public static <T> CommonResponse<T> buildError(String errorMsg) {
        return new CommonResponse(null, errorMsg, BizErrorCode.SYSTEM_BUSY_ERROR);
    }

    public T getData() {
        return data;
    }


    public int getCode() {
        return this.code;
    }


    public static <T> CommonResponse<T> result(T data) {
        return new CommonResponse<>(data);
    }


    @Override
    public String toString() {
        return "CommonResponse{" +
                "code=" + code +
                ", message='" + message + '\'' +
                ", data=" + data +
                '}';
    }
}
